<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>套餐订购</title>
    <style>
        /* 全局样式重置 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Microsoft YaHei', sans-serif;
        }
        
        body {
            background-color: #f5f5f5;
            color: #333;
        }
        
        /* 页面容器 */
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        /* 页面标题 */
        .page-title {
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 20px;
            color: #333;
        }
        
        /* 内容区域 */
        .content-area {
            background-color: #fff;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            margin-bottom: 20px;
        }
        
        /* 订购表单区域 */
        .order-form {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }
        
        /* 选择区域样式 */
        .select-section {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }
        
        .section-title {
            font-size: 18px;
            font-weight: bold;
            color: #333;
            margin-bottom: 10px;
            padding-bottom: 8px;
            border-bottom: 2px solid #2196F3;
        }
        
        /* 选择框样式 */
        .form-group {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }
        
        .form-label {
            font-weight: bold;
            color: #666;
        }
        
        .form-select {
            padding: 10px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            background-color: #fff;
            cursor: pointer;
        }
        
        .form-select:focus {
            outline: none;
            border-color: #2196F3;
            box-shadow: 0 0 0 2px rgba(33, 150, 243, 0.1);
        }
        
        /* 信息展示区域 */
        .info-display {
            background-color: #f8f9fa;
            border-radius: 4px;
            padding: 15px;
            border: 1px solid #e9ecef;
        }
        
        .info-item {
            margin-bottom: 8px;
            font-size: 14px;
        }
        
        .info-item:last-child {
            margin-bottom: 0;
        }
        
        .info-label {
            font-weight: bold;
            color: #666;
            margin-right: 8px;
        }
        
        .info-value {
            color: #333;
        }
        
        /* 价格汇总区域 */
        .price-summary {
            background-color: #e3f2fd;
            border-radius: 4px;
            padding: 15px;
            border: 1px solid #bbdefb;
        }
        
        .price-item {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
            font-size: 14px;
        }
        
        .price-item:last-child {
            margin-bottom: 0;
            font-weight: bold;
            color: #1976D2;
        }
        
        /* 按钮样式 */
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            font-size: 14px;
            font-weight: bold;
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        
        .btn-primary {
            background-color: #2196F3;
            color: white;
        }
        
        .btn-primary:hover {
            background-color: #1976D2;
        }
        
        .btn-danger {
            background-color: #f44336;
            color: white;
        }
        
        .btn-danger:hover {
            background-color: #d32f2f;
        }
        
        .btn-secondary {
            background-color: #9e9e9e;
            color: white;
        }
        
        .btn-secondary:hover {
            background-color: #757575;
        }
        
        .btn-group {
            display: flex;
            gap: 10px;
            justify-content: center;
            margin-top: 20px;
        }
        
        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.4);
            justify-content: center;
            align-items: center;
        }
        
        .modal-content {
            background-color: #fff;
            border-radius: 8px;
            padding: 20px;
            width: 90%;
            max-width: 500px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
        }
        
        .modal-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 1px solid #e9ecef;
        }
        
        .modal-title {
            font-size: 20px;
            font-weight: bold;
            color: #333;
        }
        
        .close-btn {
            background: none;
            border: none;
            font-size: 24px;
            cursor: pointer;
            color: #999;
        }
        
        .close-btn:hover {
            color: #666;
        }
        
        /* 支付表单样式 */
        .payment-form {
            display: flex;
            flex-direction: column;
            gap: 15px;
        }
        
        .payment-input {
            padding: 10px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        
        .payment-input:focus {
            outline: none;
            border-color: #2196F3;
            box-shadow: 0 0 0 2px rgba(33, 150, 243, 0.1);
        }
        
        /* 成功提示样式 */
        .success-message {
            text-align: center;
            padding: 20px;
        }
        
        .success-icon {
            font-size: 48px;
            color: #4CAF50;
            margin-bottom: 15px;
        }
        
        .success-text {
            font-size: 16px;
            color: #333;
            margin-bottom: 10px;
        }
        
        /* 响应式设计 */
        @media (max-width: 768px) {
            .container {
                padding: 10px;
            }
            
            .page-title {
                font-size: 20px;
            }
            
            .section-title {
                font-size: 16px;
            }
            
            .btn-group {
                flex-direction: column;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <h1 class="page-title" style="font-size: 1.2em;">套餐订购</h1>
        
        <div class="content-area">
            <form class="order-form" id="orderForm">
                <!-- 用户选择区域 -->
                <div class="select-section">
                    <h2 class="section-title">选择用户</h2>
                    <div class="form-group">
                        <label class="form-label" for="userId">用户</label>
                        <select id="userId" class="form-select" required>
                            <option value="">请选择用户</option>
                            <!-- 动态加载用户选项 -->
                        </select>
                    </div>
                    <div id="userInfo" class="info-display">
                        <!-- 动态显示用户信息 -->
                    </div>
                </div>
                
                <!-- 套餐选择区域 -->
                <div class="select-section">
                    <h2 class="section-title">选择套餐</h2>
                    <div class="form-group">
                        <label class="form-label" for="packageId">套餐</label>
                        <select id="packageId" class="form-select" required>
                            <option value="">请选择套餐</option>
                            <!-- 动态加载套餐选项 -->
                        </select>
                    </div>
                    <div id="packageInfo" class="info-display">
                        <!-- 动态显示套餐信息 -->
                    </div>
                </div>
                
                <!-- 优惠选择区域 -->
                <div class="select-section">
                    <h2 class="section-title">选择优惠</h2>
                    <div class="form-group">
                        <label class="form-label" for="promotionId">优惠</label>
                        <select id="promotionId" class="form-select">
                            <option value="">无优惠</option>
                            <!-- 动态加载优惠选项 -->
                        </select>
                    </div>
                    <div id="promotionInfo" class="info-display">
                        <!-- 动态显示优惠信息 -->
                    </div>
                </div>
                
                <!-- 价格汇总区域 -->
                <div class="select-section">
                    <h2 class="section-title">价格汇总</h2>
                    <div id="priceSummary" class="price-summary">
                        <div class="price-item">
                            <span>套餐原价</span>
                            <span id="originalPrice">¥0.00</span>
                        </div>
                        <div class="price-item">
                            <span>优惠金额</span>
                            <span id="discountAmount">-¥0.00</span>
                        </div>
                        <div class="price-item">
                            <span>实付金额</span>
                            <span id="finalPrice">¥0.00</span>
                        </div>
                    </div>
                </div>
            </form>
            
            <div class="btn-group">
                <button id="orderBtn" class="btn btn-primary">立即订购</button>
                <button id="resetBtn" class="btn btn-secondary">重置</button>
            </div>
        </div>
    </div>
    
    <!-- 支付模态框 -->
    <div id="paymentModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title">支付确认</h2>
                <button class="close-btn" onclick="closePaymentModal()">&times;</button>
            </div>
            
            <div class="payment-form">
                <div class="form-group">
                    <label class="form-label" for="paymentAmount">支付金额</label>
                    <input type="number" id="paymentAmount" class="payment-input" step="0.01" min="0" required readonly>
                </div>
                
                <div class="form-group">
                    <label class="form-label" for="countdown">支付剩余时间</label>
                    <div id="countdown" class="payment-input" style="background-color: #f5f5f5; padding: 10px 12px; border-radius: 4px;">
                        30:00
                    </div>
                </div>
                
                <div class="btn-group">
                    <button id="payBtn" class="btn btn-danger">确认支付</button>
                    <button id="cancelPayBtn" class="btn btn-secondary" onclick="cancelPaymentModal()">取消</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 支付成功模态框 -->
    <div id="successModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">
                <h2 class="modal-title">支付结果</h2>
                <button class="close-btn" onclick="closeSuccessModal()">&times;</button>
            </div>
            
            <div class="success-message">
                <div class="success-icon">✓</div>
                <p class="success-text" id="successText">支付成功！</p>
                <p class="success-text" id="emailText">已向用户发送确认邮件</p>
            </div>
            
            <div class="btn-group">
                <button class="btn btn-primary" onclick="closeSuccessModal()">确定</button>
            </div>
        </div>
    </div>
    
    <script>
        // 环境切换开关：'dev' 开发环境（调用本地http接口），'prod' 生产环境（调用/api接口）
        const ENV_MODE = 'prod'; // 修改此值切换环境
        
        // 全局变量存储数据
        let users = [];
        let packages = [];
        let promotions = [];
        let selectedUserId = '';
        let selectedPackageId = '';
        let selectedPromotionId = '';
        let finalPrice = 0;
        let isUserMode = false; // 标识是否从用户界面进入
        let currentOrderId = null; // 当前订单ID
        
        // 日期格式化函数
        function formatDate(date) {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            const hours = String(date.getHours()).padStart(2, '0');
            const minutes = String(date.getMinutes()).padStart(2, '0');
            const seconds = String(date.getSeconds()).padStart(2, '0');
            return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        }
        
        // 解析URL参数
        function getUrlParams() {
            const params = {};
            const urlParams = new URLSearchParams(window.location.search);
            for (const [key, value] of urlParams.entries()) {
                params[key] = value;
            }
            return params;
        }
        
        // DOM元素
        const userIdSelect = document.getElementById('userId');
        const packageIdSelect = document.getElementById('packageId');
        const promotionIdSelect = document.getElementById('promotionId');
        const userInfoDiv = document.getElementById('userInfo');
        const packageInfoDiv = document.getElementById('packageInfo');
        const promotionInfoDiv = document.getElementById('promotionInfo');
        const originalPriceSpan = document.getElementById('originalPrice');
        const discountAmountSpan = document.getElementById('discountAmount');
        const finalPriceSpan = document.getElementById('finalPrice');
        const paymentAmountInput = document.getElementById('paymentAmount');
        
        // 获取用户数据
        function fetchUsers() {
            const apiUrl = ENV_MODE === 'dev' 
                ? 'http://localhost:8181/ai/taocan/listUser' 
                : '/api/taocan/listUser';
            
            return fetch(apiUrl)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应异常');
                    }
                    return response.json();
                })
                .then(data => {
                    users = data;
                    // 如果接口返回空数据，使用模拟数据
                    if (!users || users.length === 0) {
                        users = [
                            {id: 1, userName: '张三', age: 22, occupation: '学生', monthlyBudget: 50, netDemand: 10, callDemand: 100, needIntlRoam: false, needVas: true, preferContract: 'no', extraRemark: '学生专享优惠', email: 'zhangsan@example.com'},
                            {id: 2, userName: '李四', age: 35, occupation: '商务人士', monthlyBudget: 150, netDemand: 30, callDemand: 500, needIntlRoam: true, needVas: true, preferContract: 'yes', extraRemark: '需要国际漫游', email: 'lisi@example.com'},
                            {id: 3, userName: '王五', age: 60, occupation: '退休人员', monthlyBudget: 80, netDemand: 5, callDemand: 500, needIntlRoam: false, needVas: true, preferContract: 'no', extraRemark: '需要健康服务', email: 'wangwu@example.com'},
                            {id: 4, userName: '赵六', age: 28, occupation: '自由职业者', monthlyBudget: 120, netDemand: 20, callDemand: 300, needIntlRoam: false, needVas: true, preferContract: 'no', extraRemark: '新用户', email: 'zhaoliu@example.com'},
                            {id: 5, userName: '钱七', age: 45, occupation: '企业管理人员', monthlyBudget: 200, netDemand: 50, callDemand: 500, needIntlRoam: true, needVas: true, preferContract: 'yes', extraRemark: '家庭共享', email: 'qianqi@example.com'}
                        ];
                    }
                    loadUserOptions();
                })
                .catch(error => {
                    console.error('获取用户数据失败:', error);
                    // 加载模拟用户数据
                    users = [
                        {id: 1, userName: '张三', age: 22, occupation: '学生', monthlyBudget: 50, netDemand: 10, callDemand: 100, needIntlRoam: false, needVas: true, preferContract: 'no', extraRemark: '学生专享优惠', email: 'zhangsan@example.com'},
                        {id: 2, userName: '李四', age: 35, occupation: '商务人士', monthlyBudget: 150, netDemand: 30, callDemand: 500, needIntlRoam: true, needVas: true, preferContract: 'yes', extraRemark: '需要国际漫游', email: 'lisi@example.com'},
                        {id: 3, userName: '王五', age: 60, occupation: '退休人员', monthlyBudget: 80, netDemand: 5, callDemand: 500, needIntlRoam: false, needVas: true, preferContract: 'no', extraRemark: '需要健康服务', email: 'wangwu@example.com'},
                        {id: 4, userName: '赵六', age: 28, occupation: '自由职业者', monthlyBudget: 120, netDemand: 20, callDemand: 300, needIntlRoam: false, needVas: true, preferContract: 'no', extraRemark: '新用户', email: 'zhaoliu@example.com'},
                        {id: 5, userName: '钱七', age: 45, occupation: '企业管理人员', monthlyBudget: 200, netDemand: 50, callDemand: 500, needIntlRoam: true, needVas: true, preferContract: 'yes', extraRemark: '家庭共享', email: 'qianqi@example.com'}
                    ];
                    loadUserOptions();
                });
        }
        
        // 加载用户选项
        function loadUserOptions() {
            userIdSelect.innerHTML = '<option value="">请选择用户</option>';
            users.forEach(user => {
                const option = document.createElement('option');
                option.value = user.id;
                option.textContent = `${user.userName} (${user.occupation})`;
                userIdSelect.appendChild(option);
            });
        }
        
        // 获取套餐和优惠信息
        function fetchPackagesAndPromotions() {
            const apiUrl = ENV_MODE === 'dev' 
                ? 'http://localhost:8181/ai/taocan/listTaocan' 
                : '/api/taocan/listTaocan';
            
            return fetch(apiUrl)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络响应异常');
                    }
                    return response.json();
                })
                .then(data => {
                    // 从接口返回的PackageInfoVO列表中提取套餐信息和优惠信息
                    packages = data.map(pkg => ({
                        packageId: pkg.packageId,
                        name: pkg.name,
                        price: pkg.price,
                        dataLimit: pkg.dataLimit,
                        dataUnit: pkg.dataUnit,
                        callMinutes: pkg.callMinutes,
                        smsCount: pkg.smsCount,
                        networkSpeed: pkg.networkSpeed,
                        features: pkg.features,
                        targetUsers: pkg.targetUsers,
                        description: pkg.description
                    }));
                    
                    // 收集所有优惠信息
                    const allPromotions = new Map();
                    data.forEach(pkg => {
                        if (pkg.promotionPolicyList && pkg.promotionPolicyList.length > 0) {
                            pkg.promotionPolicyList.forEach(promotion => {
                                if (!allPromotions.has(promotion.promotionId)) {
                                    allPromotions.set(promotion.promotionId, promotion);
                                }
                            });
                        }
                    });
                    
                    promotions = Array.from(allPromotions.values());
                    
                    // 加载套餐选项
                    loadPackageOptions();
                    // 初始化优惠选项
                    loadPromotionOptions();
                })
                .catch(error => {
                    console.error('获取套餐和优惠数据失败:', error);
                    // 如果接口调用失败，使用模拟数据
                    const mockPackages = [
                        {packageId: 'P001', name: '青春校园套餐', price: 39.00, dataLimit: 10, dataUnit: 'GB', callMinutes: 100, smsCount: 50, networkSpeed: '基础', features: '视频会员', targetUsers: '学生', description: '专为学生设计的经济型套餐'},
                        {packageId: 'P002', name: '商务精英套餐A', price: 99.00, dataLimit: 20, dataUnit: 'GB', callMinutes: 300, smsCount: 100, networkSpeed: '标准', features: '视频会员,音乐会员', targetUsers: '商务人士,自由职业者', description: '适合商务人士的均衡套餐'},
                        {packageId: 'P003', name: '商务精英套餐B', price: 129.00, dataLimit: 30, dataUnit: 'GB', callMinutes: 500, smsCount: 100, networkSpeed: '高速', features: '视频会员,音乐会员,健康服务', targetUsers: '商务人士,企业管理人员', description: '适合高需求商务人士的高端套餐'},
                        {packageId: 'P004', name: '家庭共享套餐', price: 199.00, dataLimit: 100, dataUnit: 'GB', callMinutes: 1000, smsCount: 200, networkSpeed: '高速', features: '国际漫游,视频会员,音乐会员,家庭共享', targetUsers: '企业管理人员,商务人士', description: '适合大家庭或小企业共享的超值套餐'},
                        {packageId: 'P005', name: '银发关爱套餐', price: 69.00, dataLimit: 5, dataUnit: 'GB', callMinutes: 500, smsCount: 200, networkSpeed: '标准', features: '健康服务,防诈骗服务', targetUsers: '退休人员', description: '针对老年用户的贴心套餐'}
                    ];
                    
                    const mockPromotions = [
                        {promotionId: 'DISCOUNT001', name: '学生专享折扣', description: '针对在校学生的特别折扣优惠', targetPackages: 'P001', discountType: 'percentage', discountValue: 10.00, eligibility: '学生', validPeriod: '长期有效'},
                        {promotionId: 'DISCOUNT002', name: '新用户首月优惠', description: '新用户首月享受特定套餐折扣', targetPackages: 'P001,P002,P003,P005', discountType: 'fixed_amount', discountValue: 10.00, eligibility: '新用户', validPeriod: '首月有效'},
                        {promotionId: 'DISCOUNT003', name: '家庭共享优惠', description: '办理家庭共享套餐享受额外折扣', targetPackages: 'P004', discountType: 'percentage', discountValue: 15.00, eligibility: '家庭用户', validPeriod: '长期有效'},
                        {promotionId: 'DISCOUNT004', name: '商务人士专属优惠', description: '为商务人士提供的专属优惠活动', targetPackages: 'P002,P003', discountType: 'percentage', discountValue: 5.00, eligibility: '商务人士', validPeriod: '季度有效'},
                        {promotionId: 'DISCOUNT005', name: '长期合约优惠', description: '签订一年以上合约享受额外优惠', targetPackages: 'P001,P002,P003,P004,P005', discountType: 'fixed_amount', discountValue: 20.00, eligibility: '长期合约用户', validPeriod: '合约期间有效'}
                    ];
                    
                    packages = mockPackages;
                    promotions = mockPromotions;
                    
                    // 加载套餐选项
                    loadPackageOptions();
                    // 初始化优惠选项
                    loadPromotionOptions();
                });
        }
        
        // 加载套餐选项
        function loadPackageOptions() {
            packageIdSelect.innerHTML = '<option value="">请选择套餐</option>';
            packages.forEach(pkg => {
                const option = document.createElement('option');
                option.value = pkg.packageId;
                option.textContent = `${pkg.name} (¥${pkg.price.toFixed(2)})`;
                packageIdSelect.appendChild(option);
            });
        }
        
        // 加载优惠选项
        function loadPromotionOptions(targetPackageId = '') {
            promotionIdSelect.innerHTML = '<option value="">无优惠</option>';
            
            // 如果选择了套餐，只显示适用该套餐的优惠
            if (targetPackageId) {
                promotions
                    .filter(promotion => promotion.targetPackages.split(',').includes(targetPackageId))
                    .forEach(promotion => {
                        const option = document.createElement('option');
                        option.value = promotion.promotionId;
                        const discountText = promotion.discountType === 'percentage' ? 
                            `${promotion.discountValue.toFixed(2)}%` : 
                            `¥${promotion.discountValue.toFixed(2)}`;
                        option.textContent = `${promotion.name} (${discountText})`;
                        promotionIdSelect.appendChild(option);
                    });
            } else {
                promotions.forEach(promotion => {
                    const option = document.createElement('option');
                    option.value = promotion.promotionId;
                    const discountText = promotion.discountType === 'percentage' ? 
                        `${promotion.discountValue.toFixed(2)}%` : 
                        `¥${promotion.discountValue.toFixed(2)}`;
                    option.textContent = `${promotion.name} (${discountText})`;
                    promotionIdSelect.appendChild(option);
                });
            }
        }
        
        // 显示用户信息
        function showUserInfo(userId) {
            const user = users.find(u => u.id == userId);
            if (user) {
                userInfoDiv.innerHTML = `
                    <div class="info-item"><span class="info-label">姓名:</span><span class="info-value">${user.userName}</span></div>
                    <div class="info-item"><span class="info-label">年龄:</span><span class="info-value">${user.age}岁</span></div>
                    <div class="info-item"><span class="info-label">职业:</span><span class="info-value">${user.occupation}</span></div>
                    <div class="info-item"><span class="info-label">月预算:</span><span class="info-value">¥${user.monthlyBudget.toFixed(2)}</span></div>
                    <div class="info-item"><span class="info-label">流量需求:</span><span class="info-value">${user.netDemand}GB</span></div>
                    <div class="info-item"><span class="info-label">通话需求:</span><span class="info-value">${user.callDemand}分钟</span></div>
                    <div class="info-item"><span class="info-label">是否需要国际漫游:</span><span class="info-value">${user.needIntlRoam ? '是' : '否'}</span></div>
                    <div class="info-item"><span class="info-label">是否需要增值服务:</span><span class="info-value">${user.needVas ? '是' : '否'}</span></div>
                    <div class="info-item"><span class="info-label">备注:</span><span class="info-value">${user.extraRemark || '无'}</span></div>
                `;
            } else {
                userInfoDiv.innerHTML = '<div class="info-item">请选择用户</div>';
            }
        }
        
        // 显示套餐信息
        function showPackageInfo(packageId) {
            const pkg = packages.find(p => p.packageId === packageId);
            if (pkg) {
                packageInfoDiv.innerHTML = `
                    <div class="info-item"><span class="info-label">套餐名称:</span><span class="info-value">${pkg.name}</span></div>
                    <div class="info-item"><span class="info-label">价格:</span><span class="info-value">¥${pkg.price.toFixed(2)}</span></div>
                    <div class="info-item"><span class="info-label">流量:</span><span class="info-value">${pkg.dataLimit} ${pkg.dataUnit}</span></div>
                    <div class="info-item"><span class="info-label">通话:</span><span class="info-value">${pkg.callMinutes}分钟</span></div>
                    <div class="info-item"><span class="info-label">短信:</span><span class="info-value">${pkg.smsCount}条</span></div>
                    <div class="info-item"><span class="info-label">网速:</span><span class="info-value">${pkg.networkSpeed}</span></div>
                    <div class="info-item"><span class="info-label">特色服务:</span><span class="info-value">${pkg.features}</span></div>
                    <div class="info-item"><span class="info-label">适用人群:</span><span class="info-value">${pkg.targetUsers}</span></div>
                    <div class="info-item"><span class="info-label">描述:</span><span class="info-value">${pkg.description}</span></div>
                `;
            } else {
                packageInfoDiv.innerHTML = '<div class="info-item">请选择套餐</div>';
            }
        }
        
        // 显示优惠信息
        function showPromotionInfo(promotionId) {
            const promotion = promotions.find(p => p.promotionId === promotionId);
            if (promotion) {
                const discountText = promotion.discountType === 'percentage' ? 
                    `${promotion.discountValue.toFixed(2)}%` : 
                    `¥${promotion.discountValue.toFixed(2)}`;
                promotionInfoDiv.innerHTML = `
                    <div class="info-item"><span class="info-label">优惠名称:</span><span class="info-value">${promotion.name}</span></div>
                    <div class="info-item"><span class="info-label">优惠类型:</span><span class="info-value">${promotion.discountType === 'percentage' ? '百分比折扣' : '固定金额优惠'}</span></div>
                    <div class="info-item"><span class="info-label">优惠金额:</span><span class="info-value">${discountText}</span></div>
                    <div class="info-item"><span class="info-label">适用套餐:</span><span class="info-value">${promotion.targetPackages}</span></div>
                    <div class="info-item"><span class="info-label">适用人群:</span><span class="info-value">${promotion.eligibility}</span></div>
                    <div class="info-item"><span class="info-label">有效期:</span><span class="info-value">${promotion.validPeriod}</span></div>
                    <div class="info-item"><span class="info-label">描述:</span><span class="info-value">${promotion.description}</span></div>
                `;
            } else {
                promotionInfoDiv.innerHTML = '<div class="info-item">无优惠</div>';
            }
        }
        
        // 计算价格汇总
        function calculatePriceSummary() {
            const pkg = packages.find(p => p.packageId === selectedPackageId);
            const promotion = promotions.find(p => p.promotionId === selectedPromotionId);
            
            let originalPrice = 0;
            let discountAmount = 0;
            
            if (pkg) {
                originalPrice = pkg.price;
                
                if (promotion) {
                    if (promotion.discountType === 'percentage') {
                        discountAmount = originalPrice * promotion.discountValue / 100;
                    } else {
                        discountAmount = promotion.discountValue;
                    }
                }
            }
            
            finalPrice = Math.max(0, originalPrice - discountAmount);
            
            originalPriceSpan.textContent = `¥${originalPrice.toFixed(2)}`;
            discountAmountSpan.textContent = `-¥${discountAmount.toFixed(2)}`;
            finalPriceSpan.textContent = `¥${finalPrice.toFixed(2)}`;
            paymentAmountInput.value = finalPrice.toFixed(2);
        }
        
        // 倒计时变量
        let countdownInterval;
        let countdownTime = 30 * 60; // 30分钟，单位：秒
        
        // 格式化倒计时时间
        function formatTime(seconds) {
            const minutes = Math.floor(seconds / 60);
            const remainingSeconds = seconds % 60;
            return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
        }
        
        // 更新倒计时显示
        function updateCountdown() {
            if (countdownTime <= 0) {
                clearInterval(countdownInterval);
                alert('支付超时，请重新下单');
                closePaymentModal();
                return;
            }
            
            countdownTime--;
            document.getElementById('countdown').textContent = formatTime(countdownTime);
        }
        
        // 创建订单并打开支付模态框
        function openPaymentModal() {
            if (!selectedUserId || !selectedPackageId) {
                alert('请选择用户和套餐');
                return;
            }
            
            // 获取当前选择的套餐和优惠信息
            const selectedUser = users.find(u => u.id == selectedUserId);
            const selectedPackage = packages.find(p => p.packageId === selectedPackageId);
            const selectedPromotion = promotions.find(p => p.promotionId === selectedPromotionId) || null;
            
            if (!selectedUser || !selectedPackage) {
                alert('用户或套餐信息无效');
                return;
            }
            
            // 构建订单数据
            const orderData = {
                userId: selectedUserId,
                userName: selectedUser.userName,
                packageId: selectedPackageId,
                packageName: selectedPackage.name,
                originalPrice: selectedPackage.price,
                discountAmount: (selectedPromotion && selectedPromotion.discountType === 'percentage') ? 
                    (selectedPackage.price * selectedPromotion.discountValue / 100) : 
                    (selectedPromotion ? selectedPromotion.discountValue : 0),
                actualPrice: finalPrice,
                status: '待支付',
                statusName: '待支付',
                createTime: formatDate(new Date())
            };
            
            // 调用创建订单接口
            const apiUrl = ENV_MODE === 'dev' 
                ? 'http://localhost:8181/ai/taocan/order/create' 
                : '/api/taocan/order/create';
            
            fetch(apiUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(orderData)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('创建订单失败');
                }
                return response.json();
            })
            .then(data => {
                if (data.code === 200 && data.data) {
                    // 保存订单ID
                    currentOrderId = data.data.id;
                    
                    // 重置倒计时
                    countdownTime = 30 * 60;
                    document.getElementById('countdown').textContent = formatTime(countdownTime);
                    
                    // 打开支付模态框
                    const paymentModal = document.getElementById('paymentModal');
                    paymentModal.style.display = 'flex';
                    
                    // 启动倒计时
                    countdownInterval = setInterval(updateCountdown, 1000);
                } else {
                    alert('创建订单失败: ' + (data.message || '未知错误'));
                }
            })
            .catch(error => {
                console.error('创建订单异常:', error);
                alert('创建订单异常，请重试');
            });
        }
        
        // 关闭支付模态框
        function closePaymentModal() {
            const paymentModal = document.getElementById('paymentModal');
            paymentModal.style.display = 'none';
            
            // 清除倒计时
            if (countdownInterval) {
                clearInterval(countdownInterval);
                countdownInterval = null;
            }
        }
        function cancelPaymentModal() {
            const paymentModal = document.getElementById('paymentModal');
            paymentModal.style.display = 'none';
            
            // 清除倒计时
            if (countdownInterval) {
                clearInterval(countdownInterval);
                countdownInterval = null;
            }
            
            // 如果有订单ID，调用取消订单接口
            if (currentOrderId) {
                const apiUrl = ENV_MODE === 'dev' 
                    ? `http://localhost:8181/ai/taocan/order/${currentOrderId}/cancel` 
                    : `/api/taocan/order/${currentOrderId}/cancel`;
                
                fetch(apiUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('取消订单失败');
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.code !== 200) {
                        console.error('取消订单失败:', data.message);
                    }
                })
                .catch(error => {
                    console.error('取消订单异常:', error);
                })
                .finally(() => {
                    // 无论成功失败，重置当前订单ID
                    currentOrderId = null;
                });
            }
        }
        
        // 打开支付成功模态框
        function openSuccessModal() {
            const successModal = document.getElementById('successModal');
            successModal.style.display = 'flex';
            
            // 模拟发送邮件
            simulateSendEmail();
        }
        
        // 关闭支付成功模态框
        function closeSuccessModal() {
            const successModal = document.getElementById('successModal');
            successModal.style.display = 'none';
            
            // 重置表单
            resetForm();
        }
        
        // 模拟支付
        function simulatePayment() {
            if (!currentOrderId) {
                alert('订单信息无效，请重新下单');
                closePaymentModal();
                return;
            }
            
            // 调用支付接口，更新订单状态
            const apiUrl = ENV_MODE === 'dev' 
                ? `http://localhost:8181/ai/taocan/order/${currentOrderId}/pay` 
                : `/api/taocan/order/${currentOrderId}/pay`;
            
            fetch(apiUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('支付失败');
                }
                return response.json();
            })
            .then(data => {
                if (data.code === 200) {
                    // 模拟支付过程
                    setTimeout(() => {
                        closePaymentModal();
                        openSuccessModal();
                    }, 1000);
                } else {
                    alert('支付失败: ' + (data.message || '未知错误'));
                }
            })
            .catch(error => {
                console.error('支付异常:', error);
                alert('支付异常，请重试');
            });
        }
        
        // 模拟发送邮件
        function simulateSendEmail() {
            const user = users.find(u => u.id == selectedUserId);
            const pkg = packages.find(p => p.packageId === selectedPackageId);
            
            if (user && pkg) {
                const emailText = document.getElementById('emailText');
                // emailText.textContent = `已向 ${user.email} 发送确认邮件`;
                emailText.textContent = `您好，您已成功订购${pkg.name}，金额为¥${finalPrice.toFixed(2)}。感谢您的使用！请随时查看邮箱关注订单生效信息。`;
                
                // 实际应用中，这里应该调用发送邮件的API
                console.log('模拟发送邮件:', {
                    to: user.email,
                    subject: '套餐订购成功通知',
                    content: `${user.userName}您好，您已成功订购${pkg.name}，金额为¥${finalPrice.toFixed(2)}。感谢您的使用！`
                });
            }
        }
        
        // 重置表单
        function resetForm() {
            userIdSelect.value = '';
            packageIdSelect.value = '';
            promotionIdSelect.value = '';
            
            selectedUserId = '';
            selectedPackageId = '';
            selectedPromotionId = '';
            
            userInfoDiv.innerHTML = '<div class="info-item">请选择用户</div>';
            packageInfoDiv.innerHTML = '<div class="info-item">请选择套餐</div>';
            promotionInfoDiv.innerHTML = '<div class="info-item">无优惠</div>';
            
            calculatePriceSummary();
        }
        
        // 初始化页面
        function initPage() {
            // 解析URL参数
            const params = getUrlParams();
            if (params.type === 'user') {
                isUserMode = true;
                console.log('进入用户模式');
                // 隐藏用户选择区域
                document.querySelector('.select-section').style.display = 'none';
            }
            
            // 绑定用户选择事件
            userIdSelect.addEventListener('change', function() {
                selectedUserId = this.value;
                showUserInfo(selectedUserId);
            });
            
            // 绑定套餐选择事件
            packageIdSelect.addEventListener('change', function() {
                selectedPackageId = this.value;
                showPackageInfo(selectedPackageId);
                loadPromotionOptions(selectedPackageId);
                selectedPromotionId = '';
                promotionIdSelect.value = '';
                showPromotionInfo(selectedPromotionId);
                calculatePriceSummary();
            });
            
            // 绑定优惠选择事件
            promotionIdSelect.addEventListener('change', function() {
                selectedPromotionId = this.value;
                showPromotionInfo(selectedPromotionId);
                calculatePriceSummary();
            });
            
            // 绑定立即订购按钮事件
            document.getElementById('orderBtn').addEventListener('click', openPaymentModal);
            
            // 绑定重置按钮事件
            document.getElementById('resetBtn').addEventListener('click', resetForm);
            
            // 绑定确认支付按钮事件
            document.getElementById('payBtn').addEventListener('click', simulatePayment);
            
            // 点击模态框外部关闭模态框
            window.addEventListener('click', function(event) {
                const paymentModal = document.getElementById('paymentModal');
                const successModal = document.getElementById('successModal');
                
                if (event.target === paymentModal) {
                    closePaymentModal();
                } else if (event.target === successModal) {
                    closeSuccessModal();
                }
            });
            
            // 加载数据
            fetchUsers().then(() => {
                // 如果是用户模式，自动选择第一个用户
                if (isUserMode && users.length > 0) {
                    selectedUserId = users[0].id;
                    userIdSelect.value = selectedUserId;
                    showUserInfo(selectedUserId);
                }
            });
            fetchPackagesAndPromotions();
        }
        
        // 页面加载完成后初始化
        window.addEventListener('load', initPage);
    </script>
</body>
</html>